<template>
  <div>
    <ul :id="id" class="ztree"></ul>
  </div>
</template>

<script>
import {deptTreeSelect} from "@/api/system/user";

export default {
  name: "DeptTreeRender",
  data() {
    let baseApi = process.env.VUE_APP_BASE_API;
    return {
      treeObj: null,
      treeNodes: [],
      deptOptions: null,
      baseAPI: baseApi,
      id: 'tree-' + Math.round(Math.random() * 100000),
    };
  },

  //组件销毁时注销地区树
  destroyed() {
    $.fn.zTree.destroy(this.id);
  },
  //初始化树结构
  mounted() {
    let _this = this;
    deptTreeSelect().then(response => {
      // this.treeNodes = response.data;
      this.treeNodes = this.filterDisabledDept(response.data);
      let setting = {
        data: {
          key: {
            name: 'label',
          }
        },
        callback: {
          //点击事件,交由父组件监听
          onClick(event, treeId, treeNode) {
            _this.$emit('select', treeNode);
          }
        }
      };
      //加载数据
      this.treeObj = $.fn.zTree.init($(`#${this.id}`), setting, this.treeNodes);
      this.treeObj.expandAll(true);
    });
  },
  methods:{
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
  }
}
</script>

<style scoped>

</style>
